package com.huawei.su;

import java.util.Stack;

/**
 * https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b?tpId=295&tqId=1008772&ru=%2Fpractice%2F6ab1d9a29e88450685099d45c9e31e46&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj
 * 链表相加
 */
public class BM11 {
    public static void main(String[] args) {
        //12367
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);

        //4567
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);
        ListNode listNode6 = new ListNode(6);
        ListNode listNode7 = new ListNode(7);

        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode6;

        listNode4.next = listNode5;
        listNode5.next = listNode6;

        listNode6.next = listNode7;

        addInList(listNode1,listNode4);
    }

    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    public static ListNode addInList(ListNode head1, ListNode head2) {
        // write code here
        int num1 = getNum(head1);
        int num2 = getNum(head2);
        return newListNode(num1 + num2);
    }

    private static ListNode newListNode(int num) {
        int length = String.valueOf(num).length();
        length--;

        ListNode head = new ListNode(num / (int) Math.pow(10, length));
        ListNode index = head;
        while (true) {
            if (length <= 0) {
                break;
            }
            length--;
            String value = String.valueOf(num / (int) Math.pow(10, length));
            int v = Integer.parseInt(String.valueOf(value.charAt(value.length() - 1)));
            index.next = new ListNode(v);

            index = index.next;
        }

        return head;
    }

    private static int getNum(ListNode head) {
        Stack<ListNode> stack = new Stack<>();
        ListNode index = head;
        while (true) {
            if (index == null) {
                break;
            }
            stack.push(index);
            index = index.next;
        }
        int num = 0;
        int count = 0;
        while (true) {
            if (stack.isEmpty()) {
                break;
            }
            num += stack.pop().val * Math.pow(10, count);
            count++;
        }
        return num;
    }
}
